package common

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os/user"
	"runtime"
	"strings"

	"github.com/spf13/viper"
)

// 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据
// contentType： 请求体格式，如：application/json
// content：     请求放回的内容
func Post(url string, data interface{}, contentType string) (string, error) {
	if contentType == "" {
		contentType = "application/json"
	}
	// 超时时间：5秒
	client := http.DefaultClient
	jsonStr, _ := json.Marshal(data)
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	result, _ := io.ReadAll(resp.Body)
	return string(result), nil
}

type PanicSrvMD struct {
	GroupID    int
	ServerID   int
	ServerType int
	Version    string
	UserName   string
	Error      string
	CrashInfo  string
	FuncArgs   string
}

func UpPanic(data *PanicSrvMD) {
	Post(viper.GetString("Config.PanicUrl")+"/srvpanic", data, "")
}

func NewPanicSrvMD(gid, stype int, sid int, version string, err interface{}, arrli ...interface{}) (result *PanicSrvMD) {
	// if version == "" {
	// 	version = appVersion.GitCommit + " @" + appVersion.BuildDate
	// }
	result = new(PanicSrvMD)
	result.GroupID = gid
	result.ServerType = stype
	result.ServerID = sid
	result.Version = version
	result.UserName = GetSystemUserName()
	result.Error = fmt.Sprint(err)
	result.CrashInfo = fmt.Sprintln(arrli...)

	return result
}

func StackTrace() string {
	sb := NewStringBuilder()
	sb.Appendln("")
	sb.Appendln("\t\t[StackTrace]:")
	for i := 1; i < 40; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		if strings.Contains(file, "/runtime/") {
			continue
		}
		sb.Appendln(fmt.Sprintf("\t\t%d. %s() %s:%d", i, runtime.FuncForPC(pc).Name(), file, line))
		// ret = fmt.Sprintf("%s\n", ret, i, runtime.FuncForPC(pc).Name(), file, line)
	}
	return sb.ToString()
}

func GetSystemUserName() string {
	if us, err := user.Current(); err != nil {
		return ""
	} else {
		return us.Username
	}
}
